package com.sharing.service;

import com.sharing.domain.User;
import com.sharing.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author MingTian
 * @version 1.0
 * @description TODO
 * @date 2023/4/4 10:48
 */
@Service("userDetailService")
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("............................................................................");
        User user = userMapper.selectUserByUserName(username);
        System.out.println(user);

        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }

        // 封装用户权限信息
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_" + user.getIdentity());

//        return new User(users.getUsername(), new BCryptPasswordEncoder().encode(users.getPassword()), auths);
        return new org.springframework.security.core.userdetails.User(user.getUserName(), user.getPassword(), auths);
    }
}
